from multiprocessing.dummy import Pool
from dateutil.parser import isoparse
import pytz
import requests
import json

import execelUtil.common.commonUtil as comutils
import execelUtil.common.commonConstants as cts


property_str = "skuCode,oldSkuCode,platform,store,suplr_code,produc_transit"


zpoNo = "ZPO23121800172"
# skuCode = "FTPLPB-0292"
bill_nolist = []
skuList  =[]
sku_str= """FTDFGF-0030"""
# skuList.append(skuCode)
# bill_nolist.append(zpoNo)


def skuInt():
    sku = dict()
    for property in property_str.split(","):
        if(property=="produc_transit"):
            sku[property]=0
        else:
            sku[property] = ""
    return sku

def checkPurTrasitQty(sku_str,size=10):
    with open('checkdata-transofpurchase-采购在途.txt', 'a', encoding='utf-8') as filewr:
        skuList = sku_str.split(",",-1)
        print(sku_str)
        res = {}
        zpo_res_list = []
        zpo_res_list_ = []
        for sku in skuList:
            param_body = comutils.getApiList()[cts.PURCHASE_ZPO_LIST_PARA_BODY]
            # param_body[comutils.PURCHASE_ZPO_LIST_PARA_BODY_ZPOID] = bill_no
            param_body[cts.PURCHASE_ZPO_LIST_PARA_BODY_SKUCODE] = sku
            response = requests.post(comutils.getApiList()[cts.PURCHASE_ZPO_LIST_URL], json=param_body,
                                     headers=comutils.getHeaders())
            # print(response.text)
            po_res = json.loads(response.text)
            po_list = po_res[cts.DATA][cts.LIST]
            # print(po_list)

            res["zpo_inv_qty"] = 0
            sum_purchase_amount = 0
            sku_oldsku_plat_store_map = dict()
            for po_no in po_list:
                year = int(po_no["poId"][2:4])
                if year < 23:
                    continue
                # po_no = po_list[0][comutils.PURCHASE_DETAIL_PARA_BODY_POID]
                zpo_param_body = comutils.getApiList()[cts.PURCHASE_DETAIL_PARA_BODY]
                zpo_param_body["poId"] = po_no["poId"]
                skulist = []
                skulist.append(sku)
                zpo_param_body[cts.PURCHASE_DETAIL_PARA_BODY_CINVCODELIST] = skulist
                # qty = int(bill_nolist[bill_no])
                # print(qty)
                zpo_response = requests.post(comutils.getApiList()[cts.PURCHASE_DETAIL_URL], json=zpo_param_body,
                                             headers=comutils.getHeaders())
                # print(zpo_response.text)
                response_data = json.loads(zpo_response.text)
                if "data" in response_data:
                    response_records = response_data["data"]
                    zpolist = response_data["data"]["poDetailEntityPageInfo"]["list"]
                    for zpo in zpolist:
                        zpo_res = dict()
                        if (zpoNo != "" and zpo["cpoId"] == zpoNo) or zpo[cts.PURCHASE_ZPO_LIST_PARA_BODY_SKUCODE] == sku:
                            produc_transit_qty = zpo["ziquantityQty"] - zpo["ireceivedQty"] - zpo["reservationQty"] - zpo["straightHairQty"] - zpo["closeQty"]
                            zpo_res["pur_zpo"] = zpo["cpoId"]
                            zpo_res["po"] = po_no["poId"]
                            zpo_res["produc_transit"] = produc_transit_qty
                            zpo_res["skuCode"] = sku
                            zpo_res["oldSkuCode"] = zpo["zoldSku"]
                            store_code = comutils.getstorelist()[zpo["store"]]
                            platfrom_code = comutils.getplatformlist()[zpo["zplatform"]]
                            oldSkuCode = zpo["zoldSku"]
                            zpo_res["store_code"] = store_code
                            zpo_res["platfrom_code"] = platfrom_code
                            zpo_res["warehouseCode"] = "01"
                            # zpo_res_list.append(zpo_res)
                            # print(res)
                            # sum_purchase_amount += produc_transit_qty
                            inv_para_body = comutils.getApiList()[cts.INV_OCCPY_PARA_BODY]
                            inv_para_body[cts.SKUCODE] = sku
                            bizType = []
                            bizType.append(cts.PUR_PRODUCE_IN_TRANSIT)
                            inv_para_body[cts.WAREHOUSECODE] = "01"
                            inv_para_body[cts.OLD_SKU_CODE] = oldSkuCode
                            inv_para_body["platform"] = platfrom_code
                            inv_para_body["store"] = store_code
                            inv_para_body["size"] = size
                            inv_para_body["current"] = 1
                            inv_para_body[cts.INV_OCCPY_BIZTYPELIST] = bizType
                            # print(inv_para_body)
                            if sku+oldSkuCode+platfrom_code+store_code not in sku_oldsku_plat_store_map:
                                response = requests.post(comutils.getApiList()[cts.INV_OCCPY_URL], json=inv_para_body,
                                                     headers=comutils.getHeaders())
                                print(response.text)
                                inv_res = json.loads(response.text)
                                inv_sku_list = inv_res[cts.DATA][cts.RECORDS]
                                sku_oldsku_plat_store_map[sku+oldSkuCode+platfrom_code+store_code]=inv_sku_list
                            inv_sku_list=sku_oldsku_plat_store_map[sku+oldSkuCode+platfrom_code+store_code]
                            zpo_res["zpo_inv_qty"] = 0
                            if len(inv_sku_list) > 0:
                                # print(inv_sku_list)
                                for inv_sku in inv_sku_list:
                                    if inv_sku["billNo"] == zpo_res["pur_zpo"]:
                                        zpo_res["zpo"] = inv_sku["billNo"]
                                        # zpo_res["site"] = inv_sku["site"]
                                        zpo_res["zpo_inv_qty"] = inv_sku["qty"]
                                        break
                                    # elif zpo_res["produc_transit"]>0:
                                    #      zpo_res["zpo"] = inv_sku["billNo"]
                                    #      zpo_res["zpo_inv_qty"] += inv_sku["qty"]
                                    #     break
                            zpo_res["produc_transit_dif"] = zpo_res["produc_transit"] - zpo_res["zpo_inv_qty"]
                            if zpo_res["produc_transit_dif"] != 0:
                                zpo_res_list.append(zpo_res)
                                print(zpo_res)
                            else:
                                zpo_res_list_.append(zpo_res)
            print(sku+":"+json.dumps(zpo_res_list))
            filewr.write(json.dumps(zpo_res_list)+"\n")
            print(sku+":"+json.dumps(zpo_res_list_))
            return zpo_res_list








def checkPurTrasitQtyWithSuplr(sku_str):
    with open('checkdata-transofpurchase-采购在途-suplr.txt', 'a', encoding='utf-8') as filewr:
        skuList = sku_str.split(",",-1)
        print(sku_str)
        res = {}
        for sku in skuList:
            zpo_res_list = []
            zpo_res_list_ = []
            param_body = comutils.getApiList()[cts.PURCHASE_ZPO_LIST_PARA_BODY]
            # param_body[comutils.PURCHASE_ZPO_LIST_PARA_BODY_ZPOID] = bill_no
            param_body[cts.PURCHASE_ZPO_LIST_PARA_BODY_SKUCODE] = sku
            response = requests.post(comutils.getApiList()[cts.PURCHASE_ZPO_LIST_URL], json=param_body,
                                     headers=comutils.getHeaders())
            # print(response.text)
            po_res = json.loads(response.text)
            po_list = po_res[cts.DATA][cts.LIST]
            # print(po_list)

            res["zpo_inv_qty"] = 0
            sum_purchase_amount = 0
            resp_qty = 0
            for po_no in po_list:
                year = int(po_no["poId"][2:4])
                if year < 23:
                    continue
                # po_no = po_list[0][comutils.PURCHASE_DETAIL_PARA_BODY_POID]
                zpo_param_body = comutils.getApiList()[cts.PURCHASE_DETAIL_PARA_BODY]
                zpo_param_body["poId"] = po_no["poId"]
                suplr_code = po_no["cvenCode"]

                skulist = []
                skulist.append(sku)
                zpo_param_body[cts.PURCHASE_DETAIL_PARA_BODY_CINVCODELIST] = skulist
                # qty = int(bill_nolist[bill_no])
                # print(qty)
                zpo_response = requests.post(comutils.getApiList()[cts.PURCHASE_DETAIL_URL], json=zpo_param_body,
                                             headers=comutils.getHeaders())
                # print(zpo_response.text)
                response_data = json.loads(zpo_response.text)

                if "data" in response_data:
                    response_records = response_data["data"]
                    zpolist = response_data["data"]["poDetailEntityPageInfo"]["list"]

                    for zpo in zpolist:
                        zpo_res = dict()
                        if (zpoNo != "" and zpo["cpoId"] == zpoNo) or zpo[cts.PURCHASE_ZPO_LIST_PARA_BODY_SKUCODE] == sku:
                            produc_transit_qty = zpo["ziquantityQty"] - zpo["ireceivedQty"] - zpo["closeQty"]- zpo["reservationQty"] - zpo["straightHairQty"]
                            zpo_res["pur_zpo"] = zpo["cpoId"]
                            zpo_res["po"] = po_no["poId"]
                            zpo_res["produc_transit"] = produc_transit_qty
                            if(produc_transit_qty==0):continue;
                            zpo_res["skuCode"] = sku
                            zpo_res["oldSkuCode"] = zpo["zoldSku"]
                            store_code = comutils.getstorelist()[zpo["store"]]
                            platfrom_code = comutils.getplatformlist()[zpo["zplatform"]]
                            oldSkuCode = zpo["zoldSku"]
                            targetDeliveryTime = zpo["targetDeliveryTime"]
                            utc_time = isoparse(targetDeliveryTime)
                            dest_zone = pytz.timezone("Asia/Shanghai")
                            dst_time = utc_time.astimezone(dest_zone)
                            zpo_res["store_code"] = store_code
                            zpo_res["platfrom_code"] = platfrom_code
                            zpo_res["warehouseCode"] = "01"
                            zpo_res["suplr_code"] = suplr_code
                            zpo_res["targetDeliveryTime"] = dst_time.strftime("%Y-%m-%d %H:%M:%S")
                            zpo_res_list.append(zpo_res)
                            resp_qty +=produc_transit_qty
            print(zpo_res_list)
            filewr.write(json.dumps(zpo_res_list)+"\n")
            print(zpo_res_list_)
            sku_resp = zpo_res_list[0] if zpo_res_list else skuInt()
            sku_resp["produc_transit"]= resp_qty
            return zpo_res_list,sku_resp
# for sku in skulist:
#     print(sku)
#     checkPurTrasitQty(sku)
#     fixdifwithunit.fixdata(checkPurTrasitQty(sku))

# checkPurTrasitQtyWithSuplr("CEETSS-0030")


skulist = [
'FTPLPT-1076'


]

pool = Pool(5)
# pool.map(checkPurTrasitQty,skulist)
pool.map(checkPurTrasitQtyWithSuplr,skulist)
# checkPurTrasitQty("FTBFVT-7009")

# fixdifwithunit.fixdata(checkPurTrasitQty("FTPLPS-0017"))